
package apps.softtech.fastmarket;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ViewFlipper;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.RequestDataFromServer;
import apps.softtech.fastmarket.adapter.AdapterFollowProduct;
import apps.softtech.fastmarket.adapter.AdapterMyProfileFollower;
import apps.softtech.fastmarket.adapter.AdapterMyProfileFollowing;
import apps.softtech.fastmarket.adapter.AdapterSearchMyProduct;
import apps.softtech.fastmarket.model.DatabaseHandler;
import apps.softtech.fastmarket.model.FollowProduct;
import apps.softtech.fastmarket.model.FollowUser;
import apps.softtech.fastmarket.model.Product;
import apps.softtech.fastmarket.model.UserInfo;

public class ActivityMyProfile extends Activity {
	Button btFollowing, btFollower, btMyProduct, btFolowProduct;
	ListView lvFollowingList, lvFollowerList, lvMyProductList,
			lvFollowProductList;
	ViewFlipper vfMyProfile;
	ArrayList<FollowUser> mFollowUsersList = new ArrayList<FollowUser>();
	ArrayList<UserInfo> mUsersFollowinList = new ArrayList<UserInfo>();
	ArrayList<UserInfo> mUsersFollowerList = new ArrayList<UserInfo>();
	ArrayList<FollowProduct> mFollowProductsList = new ArrayList<FollowProduct>();
	ArrayList<Product> mProductsList = new ArrayList<Product>();
	AdapterMyProfileFollowing myAdapterProfileFollowing;
	AdapterMyProfileFollower myAdapterProfileFollower;
	AdapterSearchMyProduct mAdapterSearchMyProduct;
	AdapterFollowProduct mAdapterFollowProduct;
	/**
	 * button click
	 */
	int bt1=0,bt2=0,bt3=0,bt4=0;
	/**
	 * check internet
	 */
	ConnectionDetector cd;
	/**
	 * display option image
	 */
	DisplayImageOptions options;
	/**
	 * database
	 */
	DatabaseHandler dbh;
	/**
	 * my id
	 */
	int myId;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_my_profile);
		
		new RegisterGoogleCM(ActivityMyProfile.this).registerGCM();
		/**
		 * init imagloader
		 */
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				ActivityMyProfile.this).build();
		ImageLoader.getInstance().init(config);
		/**
		 * init options
		 */
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(20)).build();

		init();
		initFunction();
	}

	private void init() {
		cd = new ConnectionDetector(ActivityMyProfile.this);
		dbh = new DatabaseHandler(ActivityMyProfile.this);
		//
		// button
		//
		btFollowing = (Button) findViewById(R.id.btMyProfileFollowing);
		btFollower = (Button) findViewById(R.id.btMyProfileFollower);
		btFolowProduct = (Button) findViewById(R.id.btMyProfileFollowProdcut);
		btMyProduct = (Button) findViewById(R.id.btMyProfileMyProduct);
		//
		// Listview
		//
		lvFollowingList = (ListView) findViewById(R.id.lvMyProfileFollowing);
		lvFollowerList =(ListView)findViewById(R.id.lvMyProfileFollower);
		lvMyProductList = (ListView)findViewById(R.id.lvMyProductList);
		lvFollowProductList = (ListView)findViewById(R.id.lvFollowProduct);
		//
		// view flipper
		//
		vfMyProfile = (ViewFlipper) findViewById(R.id.vfMyProfile);
		btFollowing.setTextColor(Color.parseColor("#1f76bc"));
	}

	private void initFunction() {
		firtLoad();
		btFollowing.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				btFollowing.setTextColor(Color.parseColor("#1f76bc"));
				btFollower.setTextColor(Color.parseColor("#868686"));
				btFolowProduct.setTextColor(Color.parseColor("#868686"));
				btMyProduct.setTextColor(Color.parseColor("#868686"));
				
				bt1=1;bt2=0;bt3=0;bt4=0;
				mFollowUsersList.clear();
				setDataFollowing();
				if (cd.isConnectingToInternet()) {

					dbh.deleteFollowUser(FollowUser.FOLLOW_ID + " >= ?",
							new String[] { "0" });
					new AsyncTaskFollowing().execute();
				} else {
					// loadlocal data
					mFollowUsersList = (ArrayList<FollowUser>) dbh
							.getFollowUser(null, FollowUser.TO_USER_ID + " =?",
									new String[] { "1" }, null, null);
					// 1 is MY ID
					if (mFollowUsersList.size() != 0) {
						mUsersFollowinList.clear();
						getUserInfoFollowing();
						setDataFollowing();
					}
				}
			}
			
		});
		btFollower.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				btFollowing.setTextColor(Color.parseColor("#868686"));
				btFollower.setTextColor(Color.parseColor("#1f76bc"));
				btFolowProduct.setTextColor(Color.parseColor("#868686"));
				btMyProduct.setTextColor(Color.parseColor("#868686"));
				bt1=0;bt2=1;bt3=0;bt4=0;
				mFollowUsersList.clear();
				setDataFollower();
				if (cd.isConnectingToInternet()) {

					dbh.deleteFollowUser(FollowUser.FOLLOW_ID + " >= ?",
							new String[] { "0" });
					new AsyncTaskFollower().execute();
				} else {
					mFollowUsersList = (ArrayList<FollowUser>) dbh
							.getFollowUser(null, FollowUser.FROM_USER_ID + " =?",
									new String[] { "1" }, null, null);
					if (mFollowUsersList.size() != 0) {
						mUsersFollowerList.clear();
						getUserInfoFollower();
						setDataFollower();
					}
				}
				
				
			}

			
		});
		btFolowProduct.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				btFollowing.setTextColor(Color.parseColor("#868686"));
				btFollower.setTextColor(Color.parseColor("#868686"));
				btFolowProduct.setTextColor(Color.parseColor("#1f76bc"));
				btMyProduct.setTextColor(Color.parseColor("#868686"));
				bt1=0;bt2=0;bt3=1;bt4=0;
				mFollowProductsList.clear();
				if (cd.isConnectingToInternet()) {
				dbh.deleteFollowProduct(FollowProduct.FOLLOW_ID + " >=0", null);
					new AsyncTaskGetFollowProduct().execute();
				} else {
					mProductsList = (ArrayList<Product>) dbh
							.getProduct(null,  Product.USERID + " =?", new String[]{"2"}, null, null);
					if (mProductsList.size() != 0) {
						mProductsList.clear();
						setDataFollowProduct();	
					}
				}
				vfMyProfile.setInAnimation(ActivityMyProfile.this, R.anim.in_from_right);
				vfMyProfile.setDisplayedChild(3);
				
			}
		});
		btMyProduct.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				btFollowing.setTextColor(Color.parseColor("#868686"));
				btFollower.setTextColor(Color.parseColor("#868686"));
				btFolowProduct.setTextColor(Color.parseColor("#868686"));
				btMyProduct.setTextColor(Color.parseColor("#1f76bc"));
				bt1=0;bt2=0;bt3=0;bt4=1;
				mProductsList.clear();
				if (cd.isConnectingToInternet()) {
					dbh.deleteProduct(Product.PRODUCT_ID + " >=0", null);
					new AsyncTaskGetMyProduct().execute();
				} else {
					mProductsList = (ArrayList<Product>) dbh
							.getProduct(null, 
									Product.USERID + " =?", new String[]{"2"}, null, null);
					if (mProductsList.size() != 0) {
						mProductsList.clear();
						setDataProduct();	
					}
				}
				vfMyProfile.setInAnimation(ActivityMyProfile.this, R.anim.in_from_right);
				vfMyProfile.setDisplayedChild(2);
			}
		});
	}
	/**
	 * firt load my profile
	 */
	private void firtLoad() {
//		bt1=1;bt2=0;bt3=0;bt4=0;
//		mFollowUsersList.clear();
//		if (cd.isConnectingToInternet()) {
//
//			dbh.deleteFollowUser(FollowUser.FOLLOW_ID + " >= ?",
//					new String[] { "0" });
//			new AsyncTaskFollowing().execute();
//		} else {
//			// loadlocal data
//			mFollowUsersList = (ArrayList<FollowUser>) dbh
//					.getFollowUser(null, FollowUser.TO_USER_ID + " =?",
//							new String[] { "1" }, null, null);
//			// 1 is application my user id
//			if (mFollowUsersList.size() != 0) {
//				mUsersFollowinList.clear();
//				getUserInfoFollowing();
//				setDataFollowing();
//			}
//		}
		//
		btFollowing.setTextColor(Color.parseColor("#868686"));
		btFollower.setTextColor(Color.parseColor("#1f76bc"));
		btFolowProduct.setTextColor(Color.parseColor("#868686"));
		btMyProduct.setTextColor(Color.parseColor("#868686"));
		bt1=0;bt2=1;bt3=0;bt4=0;
		mFollowUsersList.clear();
		if (cd.isConnectingToInternet()) {

			dbh.deleteFollowUser(FollowUser.FOLLOW_ID + " >= ?",
					new String[] { "0" });
			new AsyncTaskFollower().execute();
		} else {
			mFollowUsersList = (ArrayList<FollowUser>) dbh
					.getFollowUser(null, FollowUser.FROM_USER_ID + " =?",
							new String[] { "1" }, null, null);
			if (mFollowUsersList.size() != 0) {
				mUsersFollowerList.clear();
				getUserInfoFollower();
				setDataFollower();
			}
		}
	}
	/**
	 * following
	 * @author Hoai
	 *
	 */
	class AsyncTaskFollowing extends AsyncTask<Void, Void, Void> {
		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(ActivityMyProfile.this);
			pd.setMessage("Loading.....");
			pd.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {

				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(
						new RequestDataFromServer()
								.requestMyProfileFollowing(1));
				int success = jsonCategoryParentList.getInt("success");
				if (success == 1) {
					jsonData = jsonCategoryParentList.getJSONArray("data");
					for (int i = 0; i < jsonData.length(); i++) {
						JSONObject jsonList = new JSONObject(jsonData
								.getJSONObject(i).toString());
						dbh.insertFollowUser(new FollowUser(jsonList
								.getInt("st_FromUserId"), jsonList
								.getInt("st_ToUserId"), jsonList
								.getString("st_FollowDate"), jsonList
								.getInt("st_GetNotification")));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			mFollowUsersList = (ArrayList<FollowUser>) dbh.getFollowUser(null,
					FollowUser.TO_USER_ID + " =?", new String[] { "1" }, null,
					null);
			mUsersFollowinList.clear();
			getUserInfoFollowing();
			setDataFollowing();
			pd.dismiss();
			super.onPostExecute(result);
		}

	}

	/**
	 * get user info
	 */
	private void getUserInfoFollower() {
		for (int i = 0; i < mFollowUsersList.size(); i++) {
			int idUser = mFollowUsersList.get(i).getToUserId();
			dbh.deleteUserInfo(UserInfo.USERID + " >=0", null);
			new AsyncTaskGetUserById(idUser).execute();
			vfMyProfile.setInAnimation(ActivityMyProfile.this, R.anim.in_from_right);
			vfMyProfile.setDisplayedChild(1);
		}
	}
	/**
	 * get user info
	 */
	private void getUserInfoFollowing() {
		for (int i = 0; i < mFollowUsersList.size(); i++) {
			int idUser = mFollowUsersList.get(i).getFromUserId();
			dbh.deleteUserInfo(UserInfo.USERID + " >=0", null);
			new AsyncTaskGetUserById(idUser).execute();
			vfMyProfile.setDisplayedChild(0);
		}
	}

	/**
	 * set data  following list
	 */
	private void setDataFollowing() {
		myAdapterProfileFollowing = new AdapterMyProfileFollowing(
				ActivityMyProfile.this, mUsersFollowinList, options);
		lvFollowingList.setAdapter(myAdapterProfileFollowing);
	}
	/**
	 * set data follower list
	 */
	private void setDataFollower() {
		if(mUsersFollowerList.size()!=0){
		Log.v("sdfsdf:",""+mUsersFollowerList.get(0).getSt_UserId());
		}
		myAdapterProfileFollower= new AdapterMyProfileFollower(
				ActivityMyProfile.this, mUsersFollowerList, options);
		lvFollowerList.setAdapter(myAdapterProfileFollower);
	}
	/**
	 * set data my product
	 *
	 */
	private void setDataProduct(){
		mAdapterSearchMyProduct = new AdapterSearchMyProduct(ActivityMyProfile.this, mProductsList, options);
		lvMyProductList.setAdapter(mAdapterSearchMyProduct);
		
	}
	/**
	 * set product
	 */
	private void setFollowProduct() {
		mFollowProductsList = (ArrayList<FollowProduct>) dbh.getFollowProduct(null, null, null, null, null);
		Log.v("size follow product",""+mFollowProductsList.size() );
		if(mFollowProductsList.size()!=0){
			dbh.deleteProduct(Product.PRODUCT_ID + " >=0", null);
			for(int i=0;i<mFollowProductsList.size();i++){
				int IdProduct = mFollowProductsList.get(i).getProductId();
			new AsyncTaskGetProductById(IdProduct).execute();
			}
		}
		
		
	}
	/**
	 * set data follow product
	 */
	private void setDataFollowProduct() {
		mAdapterFollowProduct = new AdapterFollowProduct(ActivityMyProfile.this, mProductsList, options);
		lvFollowProductList.setAdapter(mAdapterFollowProduct);
	}
	/**
	 * get user by id
	 * @author Hoai
	 *
	 */
	class AsyncTaskGetUserById extends AsyncTask<Void, Void, Void> {

		int idUser;
		public AsyncTaskGetUserById(int id) {
			idUser = id;
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {

				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(
						new RequestDataFromServer().requestUserInfoById(idUser));
				int success = jsonCategoryParentList.getInt("success");
				if (success == 1) {
					jsonData = jsonCategoryParentList.getJSONArray("data");
					for (int i = 0; i < jsonData.length(); i++) {
						JSONObject jsonList = new JSONObject(jsonData
								.getJSONObject(i).toString());
						UserInfo uit = new UserInfo();
						uit.setUserName(jsonList.getString("st_UserName"));
						uit.setAvatarPath(jsonList.getString("st_AvatarPath"));
						uit.setSt_UserId(idUser);
						uit.setEmail(jsonList.getString("st_Email"));
						uit.setPhoneNumber(jsonList.getString("st_PhoneNumber"));
						dbh.insertUserInfo(uit);
						Log.v("", jsonList.getString("st_UserId"));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if(bt1==1){
				mUsersFollowinList= (ArrayList<UserInfo>) dbh.getUserInfo(null, null, null, null, null);
				
				setDataFollowing();
			}
			if(bt2==1){
				mUsersFollowerList= (ArrayList<UserInfo>) dbh.getUserInfo(null, null, null, null, null);
			
				setDataFollower();
			}
			super.onPostExecute(result);
		}

	}
	class AsyncTaskFollower extends AsyncTask<Void, Void, Void> {
		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(ActivityMyProfile.this);
			pd.setMessage("Loading.....");
			pd.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				//
				//test
				//
//				new RequestDataFromServer().requestRegisterFollowProduct(18);
//				new RequestDataFromServer().requestRegisterFollowProduct(19);
//				new RequestDataFromServer().requestRegisterFollowProduct(20);
				//
				// ok test
				//
				
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(
						new RequestDataFromServer()
								.requestMyProfileFollower(2));
				int success = jsonCategoryParentList.getInt("success");
				if (success == 1) {
					jsonData = jsonCategoryParentList.getJSONArray("data");
					for (int i = 0; i < jsonData.length(); i++) {
						JSONObject jsonList = new JSONObject(jsonData
								.getJSONObject(i).toString());
						dbh.insertFollowUser(new FollowUser(jsonList
								.getInt("st_FromUserId"), jsonList
								.getInt("st_ToUserId"), jsonList
								.getString("st_FollowDate"), jsonList
								.getInt("st_GetNotification")));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			mFollowUsersList = (ArrayList<FollowUser>) dbh.getFollowUser(null,
					FollowUser.FROM_USER_ID + " =?", new String[] { "2" }, null,
					null);
			mUsersFollowerList.clear();
			getUserInfoFollower();
			setDataFollower();
			pd.dismiss();
			super.onPostExecute(result);
		}

	}
	/**
	 * 
	 * get my product
	 *
	 */
	class AsyncTaskGetMyProduct extends AsyncTask<Void, Void, Void>{
		ProgressDialog pd;
		
		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(ActivityMyProfile.this);
			pd.setMessage("Loading....");
			pd.show();
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			try{
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(new RequestDataFromServer().requestMyProductd(2));
				int success = jsonCategoryParentList.getInt("success");
				if(success==1){
					jsonData = jsonCategoryParentList.getJSONArray("data");
					Log.v("", jsonData.toString());
					for(int i=0;i<jsonData.length();i++){
						JSONObject jsonList = new JSONObject(jsonData.getJSONObject(i).toString());
//						
						Product mpProduct = new Product();
						mpProduct.setPrice(jsonList.getInt("st_Price"));
						mpProduct.setAvatarPath(jsonList.getString("st_AvatarPath"));
						mpProduct.setCreatedDate(jsonList.getString("st_CreatedDate"));
						dbh.insertProduct(mpProduct);
						mProductsList.add(mpProduct);
					}
				}
				}catch(Exception e){}
				Log.v("", "");
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			setDataProduct();
			pd.dismiss();
			super.onPostExecute(result);
		}
	}
	/**
	 * 
	 * get product follow
	 *
	 */
	class AsyncTaskGetFollowProduct extends AsyncTask<Void, Void, Void>{
		ProgressDialog pd;
		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(ActivityMyProfile.this);
			pd.setMessage("Loading....");
			pd.show();
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			try{
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(new RequestDataFromServer()
				.requestFollowProduct());
				int success = jsonCategoryParentList.getInt("success");
				if(success==1){
					jsonData = jsonCategoryParentList.getJSONArray("data");
					
					for(int i=0;i<jsonData.length();i++){
						JSONObject jsonList = new JSONObject(jsonData.getJSONObject(i).toString());

						FollowProduct fp = new FollowProduct();
						fp.setUserId(jsonList.getInt("st_UserId"));
						fp.setProductId(jsonList.getInt("st_ProductId"));
						fp.setFollowDate(jsonList.getString("st_FollowDate"));
						fp.setGetNotificaton(jsonList.getInt("st_GetNotification"));
						dbh.insertFollowProduct(fp);
						mFollowProductsList.add(fp);

						Log.v("", jsonList.toString());
						dbh.insertFollowProduct(new FollowProduct(
								jsonList.getInt("st_UserId"), jsonList.getInt("st_ProductId"),
								jsonList.getString("st_FollowDate"), jsonList.getInt("st_GetNotification"),0));

					}
				}
				}catch(Exception e){
					Log.v("loi~: ", e.toString());
				}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			setFollowProduct();
			setDataFollowProduct();
			pd.dismiss();
			super.onPostExecute(result);
		}
	}
	/**
	 * get product by id product
	 */
	class AsyncTaskGetProductById extends AsyncTask<Void, Void, Void>{
		int IdProduct;
		public AsyncTaskGetProductById(int id){
			IdProduct =id;
		}
		@Override
		protected Void doInBackground(Void... params) {
			try{
				JSONObject jsonData = new JSONObject();
				JSONObject jsonCategoryParentList = new JSONObject(new RequestDataFromServer().requestGetProductById(IdProduct));
				int success = jsonCategoryParentList.getInt("success");
				if(success==1){
					jsonData = jsonCategoryParentList.getJSONObject("data");
					
						Product mpProduct = new Product();
						mpProduct.setPrice(jsonData.getInt("st_Price"));
						mpProduct.setAvatarPath(jsonData.getString("st_AvatarPath"));
						mpProduct.setCreatedDate(jsonData.getString("st_CreatedDate"));
						dbh.insertProduct(mpProduct);
						
				}
				}catch(Exception e){
					Log.v("errors: ", e.toString());
				}
			return null;
		}
		
	}
	
@Override
protected void onDestroy() {
	dbh.close();
	super.onDestroy();
}
}

